﻿using System;
using System.Data.Linq;
using Lilium.Data.Repository;
using Lilium.Unity.ContainerConfiguration;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using Lilium.Unity.LifetimeManagers;

namespace Lilium.Web.Mvc
{
	//TODO: Убрать отсюда, т.к. никакого отношения к Mvc это не имеет.
	/// <summary>
	/// <see cref="DataContextAttribute"/> used to configure <see cref="DataContext"/> injection for <see cref="EntityController">entity controllers</see>.
	/// </summary>
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
	public sealed class DataContextAttribute : Attribute, IContainerConfigurator
	{
		public DataContextAttribute(Type dataContextType)
		{
			if (dataContextType == null) throw new ArgumentNullException("dataContextType");

			m_DataContextType = dataContextType;
		}

		#region public object ConstructorParamters

		private object m_ConstructorParamters;

		public object ConstructorParamters
		{
			//[System.Diagnostics.DebuggerNonUserCodeAttribute]
			get
			{
				return m_ConstructorParamters;
			}
			//[System.Diagnostics.DebuggerNonUserCodeAttribute]
			set
			{
				m_ConstructorParamters = value;
			}
		}

		#endregion

		#region public Type DataContextType

		private readonly Type m_DataContextType;

		public Type DataContextType
		{
			//[System.Diagnostics.DebuggerNonUserCodeAttribute]
			get
			{
				return m_DataContextType;
			}
		}

		#endregion

        #region IBuildConfigurator Members

        public void ConfigureContainer(IUnityContainer container, NamedTypeBuildKey buildKey)
        {
            if (container == null) throw new ArgumentNullException("container");
            if (buildKey == null) throw new ArgumentNullException("buildKey");

            container.RegisterType(typeof(DataContext), DataContextType, buildKey.Name);
            container.RegisterType(DataContextType, buildKey.Name, new PerRequestLifetimeManager(), new InjectionConstructor());
            container.RegisterType(typeof(IRepositoryProvider), typeof(DataContextAdapter), buildKey.Name);
        }

        #endregion
    }
}